<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use EasyWeChat\Kernel\Support\XML;

/**
 * 订单
 */
class Goods extends Api
{


	protected $noNeedLogin = ['notify'];
	protected $noNeedRight = '*';

	/**
	 * 认购单价
	 */
	public function single_price()
	{
		$money = 69;
		$this->success("正常", $money);
	}

	/**
	 * 认购
	 */
	public function sub_buy()
	{
		$uid = $this->auth->id;
		$price = $this->request->post("price");
		$nums  = $this->request->post("nums");
		$pay   = $this->request->post("payTyp");
		$openid   = $this->request->post("openid");
		if (!empty($price) && !empty($nums) && !empty($pay)) {
			$payMoney = bcmul((string)$price, (string) $nums, 2);
			$limit_nums = \app\api\controller\basics\Basics::instance()->buy_limit_nums($uid);
			if ($limit_nums < $nums) {
				$this->error("认购数量不能大于" . $limit_nums);
			} else {
				$regMsg = Config("msg");
				// $check_balance_pay = true;
				if ($pay == "YE") {
					$balance = \app\api\controller\basics\Basics::instance()->get_balance($uid);
					if ($payMoney > $balance) {
						$this->error($regMsg["0102"], 0);
					}
				}
				if ($pay == "W") {
					if (empty($openid)) {
						$this->error($regMsg["0003"], 0);
					}
				}
				// if (true) {
				Db::startTrans();
				$flag = false;
				$reg = "0000";
				$responce = [];
				$option = [];
				$changeBalanceOption = [];
				// 认购等级
				$buy_level = \app\api\controller\basics\Basics::instance()->get_buy_levels($nums);
				// 唯一订单号
				$order_sn = \app\api\controller\basics\Basics::instance()->createUniqueNo();
				$pid = \app\api\controller\basics\Basics::instance()->pid($uid);
				$option = [
					"order_num" => $order_sn,
					"agid" 	=> $uid,
					"pid"	=> $pid,
					"buy_level" => $buy_level,
					"nums" => $nums,
					"single_price" => $price,
					"money" => $payMoney,
					"pay_type" => $pay,
					"pay_status" => 2,
					"create_time" => time(),
					"mome" => \app\api\controller\basics\Basics::instance()->get_user_name($uid) . "-终端认购"
				];
				$id = Db::name("equip_buy")->insertGetId($option);
				if ($id) {
					if ($pay == "YE") {
						// 代理记录 增+减 - 余额操作
						$changeBalanceOption = [
							"aid"		=> $pid, 		// 增 - 代理ID
							"sid"		=> $uid, 		// 减 - 代理ID
							"typs"		=> 8, 			// 变更类型 1=分润,2=达标,3=流量卡,4=借款,5=还款,6=赠送,7=提现,8=认购 。。。。。。等
							"isChg" 	=> "1_2", 		// 1 收入 2 支出 传 顺序 => 加_减[1_2]
							"remark" 	=>  \app\api\controller\basics\Basics::instance()->get_user_name($uid) . "-终端认购收入_终端认购-支出",	// 备注  => 加减顺序 下划线 (_) 隔开 如：加_减
							"chgAmt" 	=> $payMoney,	// 变更金额
							"ids" 		=> $id,			// 操作订单主ID ，注： 分润、达标、流量卡 传入产品ID
						];
						$req = \app\common\controller\Balance::instance()->comp_and_log($changeBalanceOption);
						if ($req) {
							// 更新 代理 等级
							$user_ret = \app\api\controller\basics\Basics::instance()->user_level_update($uid, $buy_level);
							if ($user_ret) {
								//  更新订单支付状态
								$order_ret = \app\api\controller\basics\Basics::instance()->buy_order_status_update($id);
								if ($order_ret) {
									$reg = "0400";
									$this->buy_nums_store($uid, $nums);
									$flag = true;
									Db::commit();
								}
							}
						}
					} else {
						$reg = "0004";
						$notify_url = Config("app_url") . "/api/goods/notify";
						$wx = new \app\common\func\WxPay($notify_url);
						$responce = $wx->pushOrder("终端认购", $openid, $option["order_num"], $option["money"]);
						$flag = true;
						Db::commit();
					}
				}
				if ($flag) {
					$this->success($regMsg[$reg], $responce);
				} else {
					$this->error($regMsg["0401"]);
					Db::rollback();
				}
				// }
			}
		}
		$this->error("认购信息有误！");
	}

	/**
	 * 微信支付 - 回调
	 */
	public function notify()
	{
		$data = file_get_contents("php://input");
		$responce = XML::parse($data);
		\app\api\controller\balance\Buying::instance()->wechat_pay_notic($responce);
		$reqMsg = Config("msg");
		$result = ['return_code' => 'SUCCESS', 'return_msg' => $reqMsg["0005"]];
		$where = ["order_num" => $responce["out_trade_no"]];
		$order = Db::name("equip_buy")
			->where($where)
			->field("id,agid,pid,buy_level,nums,money,pay_status,mome")
			->find();
		if ($order || $order["pay_status"] != 1) {
			// return_code 表示通信状态，不代表支付状态
			if ($responce["return_code"] === 'SUCCESS') {
				$update = [];
				// 用户是否支付成功
				if ($responce["result_code"] === 'SUCCESS') {
					$update = [
						"pay_status" => 1,
						"mome" => explode("_", $order["mome"])[0] . "_" . $reqMsg["0005"]
					];
				} else {
					$update = [
						"pay_status" => 3,
						"mome" => explode("_", $order["mome"])[0] . "_" . $reqMsg["0006"]
					];
				}
				$update["pay_time"]  = time();
				$order_ret = Db::name("equip_buy")->where("id=" . $order["id"])->update($update);
				if ($order_ret) {
					if ($update["pay_status"] == 1) {
						$flag = false;
						Db::startTrans();
						// // 代理记录 上级 - 增 - 余额操作
						$changeBalanceOption = [
							"uid"		=> $order["pid"], 		// 增 - 代理ID
							"typs"		=> 8, 			// 变更类型 1=分润,2=达标,3=流量卡,4=借款,5=还款,6=赠送,7=提现,8=认购 。。。。。。等
							"isChg" 	=> "1", 		// 1 收入
							"remark" 	=>  \app\api\controller\basics\Basics::instance()->get_user_name($order["agid"]) . "-终端认购收入",	// 备注 
							"chgAmt" 	=> $order["money"],	// 变更金额
							"ids" 		=> $order["id"],			// 操作订单主ID ，注： 分润、达标、流量卡 传入产品ID
						];
						$req = \app\common\controller\Balance::instance()->add_and_logs($changeBalanceOption);
						if ($req) {
							// 更新 代理 等级
							$user_ret = \app\api\controller\basics\Basics::instance()->user_level_update($order["agid"], $order["buy_level"]);
							if ($user_ret) {
								$this->buy_nums_store($order["agid"], $order["nums"]);
								$flag = true;
								Db::commit();
							}
						}
						if ($flag === false) {
							Db::rollback();
						}
					}
				}
			} else {
				$result = ["return_code" => "FAIL", "return_msg" => $reqMsg["0007"]];
			}
		}
		return XML::build($result);
	}

	/**
	 * 认购数存储
	 */
	public function buy_nums_store($uid = 0, $nums = 0, $proid = 0)
	{
		if (!empty($uid) && !empty($nums)) {
			$where = "agid = " . $uid;
			$check = Db::name("equip_buy_nums")->where($where)->count();
			if ($check) {
				$update = [
					"nums" => Db::raw("nums" . " + " . $nums)
				];
				Db::name("equip_buy_nums")->where($where)->update($update);
			} else {
				$option = [
					"agid" => $uid,
					"product_id" => $proid,
					"nums" => $nums
				];
				Db::name("equip_buy_nums")->insert($option);
			}
		}
	}
}
